<template>
	<!-- <uni-file-picker :auto-upload="false" v-model="fileList" file-mediatype="all" mode="grid" @select="select" file-extname="png,jpg,mp4"
		ref="upload" @progress="progress" @success="success" @fail="fail" /> -->
	<!-- <button class="button" type="primary" @click="upload">上传文件</button> -->
	<view class='uploadClass'>
		<view class='imgClass' v-for="(item,index) in fileList" :key="item.fileUrl">
			<image-view v-if="item.from==1" :src="item.showUrl" style="width:100%;height: 100%;"></image-view>
			<image @click="big(fileList,index)"
				v-if="item.from!=1 && (item.type=='jpeg'||item.type=='png'||item.type=='jpg')" :src="item.showUrl">
			</image>
			<!-- <video v-if="item.type=='mp4'" :src="baseUrl+item.fileUrl" :autoplay="false"></video> -->
			<view class="delete" @click="deleteItem(index)">
				<image src="../../static/images/delete.png"></image>
			</view>
		</view>
		<view class='imgClass' v-for="(item,index) in uploadingFileList" :key="item.path">
			<image :src="item.path"></image>
		</view>
		<view class='imgClass' @click="upload" v-if="fileList.length<1 && uploadingFileList.length===0">
			+
		</view>
		<canvas canvas-id="canvas"
			:style="{width:cWicth+'px',height:cHeight+'px',position:'absolute',left:'-1000px',top:'-1000px'}"></canvas>
		<uni-popup ref="popup" background-color="#fff" :mask-click="false">
			<view class="popup-content">
				<view style="text-align: center;">
					<uni-icons type="spinner-cycle" size="30"></uni-icons>
				</view>
				<view class="text">图片正在上传，请等待....</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		pathToBase64,
		base64ToPath
	} from '@/utils/base64.js'
	import {
		getImg,
		uploadBase64
	} from '@/api/work/equipment.js'
	export default {
		data() {
			return {
				baseUrl: '/fileUpload/',
				fileList: [],
				uploadingFileList: [],
				cHeight: 0,
				cWicth: 0
			}
		},
		methods: {
			setFileList(list) {
				this.fileList = list
			},
			initFile(e) {
				if (e != null && e.length > 0) {
					var files = e.split(";")
					var list = []
					for (var i = 0; i < files.length; i++) {
						list.push({
							type: files[i].split('.')[1],
							fileUrl: files[i]
						})
					}
					this.fileList = list
				} else {
					this.fileList = []
				}
			},
			big(fileList, index) {
				var list = []
				for (var a = 0; a < fileList.length; a++) {
					// list.push('/fileApi/' + fileList[a].fileUrl)
					list.push(fileList[a].fileUrl)
				}
				uni.previewImage({
					current: index,
					urls: list, //需要预览的图片http链接列表，多张的时候，url直接写在后面就行了
				})
			},
			deleteItem(index) {
				this.imageUrl()
				this.fileList.splice(index, 1)
				this.$emit('uploadSuccess', this.fileList);
			},
			upload() {
				var minTempFilePath = ''
				var that = this
				uni.chooseImage({
					sizeType: ['compressed'], // original 原图，compressed 压缩图，默认二者都有
					sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
					success: (res) => {
						const tempFiles = res.tempFiles;
						const tempFilePaths = res.tempFilePaths;

						for (let i = 0; i < tempFiles.length; i++) {
							//遮罩显示
							// this.$refs.popup.open()
							const imgSize = tempFiles[i] && tempFiles[i].size ? tempFiles[i].size : 0;
							const imgName = tempFiles[i] && tempFiles[i].name ? tempFiles[i].name : '';
							setTimeout(() => {
								uni.showLoading({
									title: "上传中",
									mask: true,
								});
							}, 0)
							this.uploadingFileList = tempFiles
							// 加载页面 动画
							setTimeout(() => {
								this.photoCompress(tempFiles[i], (base64Codes) => {
									var fl = this.dataURLtoFile(base64Codes, imgName)
									// var params = {
									//  // name: 'file',
									//  // // filePath: res.tempFilePath,
									//  // header: {
									//  // 	'Authorization': 'Bearer ' + uni.getStorageSync(
									//  // 		'token'),
									//  // },
									//  formData: {
									//  	// file: tempFiles[0] // 后端接收的其他参数
									//  	file: base64
									//  },
									// }
									const CONFIG = window.config.common;
									const openSecurity = CONFIG.openSecurity;
									//开启总线
									// if (openSecurity) {
									// 	var params = base64Codes
									// 	uploadBase64(params).then(uploadFileRes => {
									// 		uploadFileRes = uploadFileRes
									// 		// if (uploadFileRes.statusCode == 200) {
									// 		// 	let res = JSON.parse(uploadFileRes.data)

									// 		this.fileList.push({
									// 			type: tempFiles[i].name.split(
									// 				'.')[1],
									// 			fileUrl: uploadFileRes.data
									// 				.relativePath,
									// 			showUrl: base64Codes
									// 		})
									// 		this.imageUrl(this.fileList[0].fileUrl)

									// 	}).finally(() => {
									// 		this.uploadingFileList = this
									// 			.uploadingFileList.filter(p => p
									// 				.path !== tempFilePaths[i])
									// 		if (this.uploadingFileList.length === 0) {
									// 			uni.hideLoading();
									// 		}
									// 	})
									// } else {
									// 	console.log(fl)
									// 	console.log(tempFiles[0])
									// 	uni.uploadFile({
									// 		url: '/universe/manage/fileUpload', //仅为示例，非真实的接口地址
									// 		name: 'file',
									// 		// filePath: res.tempFilePath,
									// 		header: {
									// 			'Authorization': 'Bearer ' + uni.getStorageSync('token'),
									// 			'X-Authorization': 'ft_universe_q1w2e3r4'
									// 		},
									// 		formData: {
									// 			file: fl // 后端接收的其他参数
									// 			// file: base64
									// 		},
									// 		success: (uploadFileRes) => {

									// 			uploadFileRes = JSON.parse(
									// 				uploadFileRes.data)
									// 			// if (uploadFileRes.statusCode == 200) {
									// 			// 	let res = JSON.parse(uploadFileRes.data)
									// 			console.log(uploadFileRes.data)

									// 			this.fileList.push({
									// 				type: tempFiles[i].name
									// 					.split('.')[1],
									// 				fileUrl: uploadFileRes
									// 					.data.relativePath,
									// 				showUrl: '/fileApi/' +
									// 					uploadFileRes.data
									// 					.relativePath
									// 			})
									// 			this.imageUrl(this.fileList[0]
									// 				.fileUrl)

									// 			// pathToBase64(tempFilePaths[i])		//图像转base64工具
									// 			//   .then(base64 => {
									// 			// 	this.fileList.push({
									// 			// 		type: tempFiles[i].name.split('.')[1],
									// 			// 		fileUrl: uploadFileRes.data.relativePath,
									// 			// 		showUrl:base64
									// 			// 	})
									// 			// 	this.imageUrl(this.fileList[0].fileUrl)
									// 			//   })
									// 			//   .catch(error => {
									// 			//   })

									// 			// 	this.$emit('uploadSuccess', this.fileList);
									// 			// }
									// 			// setTimeout(function(){
									// 			// 	getImg('/'+uploadFileRes.data.relativePath).then(res => {
									// 			// 		// this.$r.toast().show();
									// 			// 	})
									// 			// },1000)

									// 			this.uploadingFileList = this
									// 				.uploadingFileList.filter(p =>
									// 					p.path !== tempFilePaths[i]
									// 				)

									// 			if (this.uploadingFileList
									// 				.length === 0) {
									// 				uni.hideLoading();
									// 			}
									// 		}
									// 	});
									// }
									uploadBase64(tempFiles[0]).then(uploadFileRes => {
										uploadFileRes = uploadFileRes
										// if (uploadFileRes.statusCode == 200) {
										// 	let res = JSON.parse(uploadFileRes.data)

										this.fileList.push({
											type: tempFiles[i].name.split('.')[
												1],
											// fileUrl: uploadFileRes.data.relativePath,
											fileUrl: uploadFileRes.data
												.fullPath,
											showUrl: base64Codes
										})
										this.imageUrl(this.fileList[0].fileUrl)

									}).finally(() => {
										this.uploadingFileList = this
											.uploadingFileList.filter(p => p.path !==
												tempFilePaths[i])
										if (this.uploadingFileList.length === 0) {
											uni.hideLoading();
										}
									})
								})
							}, 100);

							// var type = tempFilePaths[i].tempFilePath.split('.')[1]

							// uni.compressImage({
							//   src: tempFilePaths[i].tempFilePath,
							//   quality: 80,
							//   success: res => {
							// 		minTempFilePath=res.tempFilePath
							// 		uni.uploadFile({
							// 			url: '/fileApi/fileUpload', //仅为示例，非真实的接口地址
							// 			name: 'file',
							// 			filePath: res.tempFilePath,
							// 			header: {
							// 				'Authorization': 'Bearer ' + uni.getStorageSync('token'),
							// 			},
							// 			success: (uploadFileRes) => {

							// 				// if (uploadFileRes.statusCode == 200) {
							// 				// 	let res = JSON.parse(uploadFileRes.data)
							// 				// 	this.fileList.push({
							// 				// 		type: tempFilePaths[i].tempFilePath.split('.')[1],
							// 				// 		fileUrl: res.fileUrl
							// 				// 	})
							// 				// 	this.$emit('uploadSuccess', this.fileList);
							// 				// }
							// 			}
							// 		});

							//   },
							//   fail:res=>{
							//   }
							// })
						}
					},
					complete: (r) => {
						// 遮罩关闭
						// this.$refs.popup.close()

					}
				});
			},
			photoCompress(file, objDiv) {
				var ready = new FileReader();
				ready.readAsDataURL(file);
				const _this = this;
				ready.onload = function() {
					var fileResult = this.result;
					_this.canvasDataURL(fileResult, objDiv)
				}
			},
			canvasDataURL(path, callback) {
				var img = new Image();
				img.src = path;
				var objCompressed = {
					width: 300
				}
				img.onload = function() {
					var that = this;

					//默认压缩后图片规格
					var quality = 1 //0.7;
					var w = that.width;
					var h = that.height;
					var scale = w / h;
					//实际要求
					w = objCompressed.width || w;
					w = Math.min(that.width, objCompressed.width);
					h = objCompressed.height || (w / scale);
					//生成canvas
					var canvas = document.createElement('canvas');
					var ctx = canvas.getContext('2d');
					// 创建属性节点
					var anw = document.createAttribute("width");
					anw.nodeValue = w;
					var anh = document.createAttribute("height");
					anh.nodeValue = h;
					canvas.setAttributeNode(anw);
					canvas.setAttributeNode(anh);
					ctx.drawImage(that, 0, 0, w, h);

					var base64 = canvas.toDataURL('image/jpeg', quality);
					// 回调函数返回base64的值
					callback(base64);
				}
			},
			dataURLtoFile(dataurl, filename) {
				var arr = dataurl.split(","),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n);
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new File([u8arr], filename, {
					type: mime
				});
			},
			imageUrl(data) {
				this.$emit("urlArr", data)
			},
			clear() {
				this.fileList = []
			}
		}
	}
</script>
<style scoped>
	.uploadClass {
		width: 100%;
		height: auto;
		display: flex;
		justify-content: flex-start;
		align-items: center;
		flex-wrap: wrap;
	}

	.imgClass {
		width: 70px;
		height: 70px;
		margin: 5px;
		border: 1px solid #adadad;
		border-radius: 5px;
		display: flex;
		font-size: 30px;
		color: #adadad;
		align-items: center;
		justify-content: center;
		position: relative;
	}

	.imgClass image {
		width: 100%;
		height: 100%;
	}

	.imgClass video {
		width: 100%;
		height: 100%;
	}

	.delete {
		position: absolute;
		top: 0;
		right: 0;
		width: 25px;
		height: 25px;
		border-radius: 0 0 0 100%;
		background-color: red;
		display: flex;
	}

	.delete image {
		width: 13px;
		height: 13px;
		position: relative;
		left: 9px;
		top: 5px;
	}

	.popup-content {
		align-items: center;
		justify-content: center;
		padding: 15px;
		height: 200rpx;
		background-color: #fff;
	}

	.text {
		padding: 20rpx 0;
	}
</style>